import 'dart:convert';
import 'dart:io';
import 'package:audio_waveforms/audio_waveforms.dart';
import 'package:docx_template/docx_template.dart';
import 'package:ffmpeg_kit_flutter_new/ffmpeg_kit.dart';
import 'package:ffmpeg_kit_flutter_new/return_code.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_app_minimizer_plus/flutter_app_minimizer_plus.dart';
import 'package:flutter_overlay_window/flutter_overlay_window.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';
import 'package:smart_translator/app/db/DbDAOHelper.dart';
import 'package:smart_translator/app/event/DataCallBack.dart';
import 'package:smart_translator/app/widgets/CommonWidgets.dart';
import 'package:wakelock_plus/wakelock_plus.dart';
import '../../../const/AppConst.dart';
import '../../../db/database.dart';
import '../../../style/app_colors.dart';
import '../../../utils/CommonUtil.dart';
import '../../../utils/tips.dart';
import '../../../views/controller/RecordTransciptSummeryController.dart';
import '../../../views/controller/RecordTranscriptViewAiController.dart';
import '../../../views/controller/RecordTranscriptViewRecordingController.dart';
import 'package:audioplayers/audioplayers.dart';

import '../../home/controllers/home_controller.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:flutter_quill/flutter_quill.dart' as quill;

class RecordscriptDetailController extends GetxController {

  var summeryChecked =  false.obs;
  var recordSCriptChecked = true.obs;
  var aiAnswerChecked = false.obs;


  var session = Session(id: 0, user_id: 0, folder_id: 0, audio_length: 0,
      session_name: '', s_name: '', s_type: '', has_read: false,
      audio_path: '', audio_size: '',
      create_time: DateTime.now(), update_time: DateTime.now()).obs;

  String? sessionId;
  String? audioType;

  var folderName = ''.obs;

  AudioPlayer? audioPlayer;
  var audioPlay = false.obs;

  final ScrollController scrollController = ScrollController();
  var isHeaderVisible = false.obs;


  final PlayerController playerController = PlayerController();
  var waveformData = RxList<double>();

  var fileLengthInDuration = '00:00:00'.obs;
  int maxFileLengthDuration = 0;

  var currentFileDuration = '00:00:00'.obs;
  int currentMillionSecondsDuration = 0;

  var speed_icon_path = 'assets/images/icon_player_speed_1.svg'.obs;


  RxList<ExtendFolderData> folderCollections = RxList<ExtendFolderData>();

  var allFolerHasChecked = false.obs;

  var exportMP3Checked = false.obs;
  var exportWAVChecked = false.obs;

  var exportSummeryTxt = false.obs;
  var exportSummerySRT = false.obs;
  var exportSummeryDocx = false.obs;
  var exportSummeryPDF = false.obs;

  var exportTranscript_withTime = false.obs;
  var exportTranscript_withName = false.obs;

  static const double _scrollThreshold = 100.0;

  double audioRateValue = 1;

  @override
  void onInit() {
    super.onInit();

    sessionId = Get.parameters['sessionId']!;
    audioType = Get.parameters['audioType']!;
    loadData();

    Get.put(RecordTranscriptViewRecordingController(sessionId,audioType));
    Get.put(RecordTranscriptViewAiController());
    Get.put(RecordTransciptSummeryController(sessionId!));

    WakelockPlus.enable();

    // 监听滚动事件
    scrollController.addListener(_onScroll);

    getCustomerFolders();
  }


  // 处理滚动事件
  void _onScroll() {
    // 获取当前滚动位置
    final currentScroll = scrollController.position.pixels;
    print('currentScroll ::: ${currentScroll}');
    // todo 固定工具栏.
    // currentScroll == 190.5 的时候，再总结页面，编辑状态时,应该把工具栏固定在顶部.
    if (scrollController.position.userScrollDirection ==
        ScrollDirection.forward) {
        if (currentScroll <= -_scrollThreshold) { // 注意：pixels 为负值表示下拉
            WidgetsBinding.instance.addPostFrameCallback((_) {
              isHeaderVisible.value = true;
            });
        }
    }
    // 当用户向下滚动时隐藏header
    else if (scrollController.position.userScrollDirection ==
        ScrollDirection.reverse) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        isHeaderVisible.value = false;
      });
    }

  }

  loadData() {
    DbDAOHelper().obtainSessionBySessionId(int.parse(sessionId!)).then((sessions) async {
      print('sessions.isNotEmpty :::  ${sessions.isNotEmpty}');
      if (sessions.isNotEmpty) {
        session.value = sessions[0];

        if(session.value.folder_id == AppConst.FOLDER_TYPE_UN_CLASSIFIED) {
           folderName.value = '未分类';
        } else if(session.value.folder_id == AppConst.FOLDER_TYPE_RUBBISH) {
          folderName.value = '回收站';
        }  else {
            DbDAOHelper().obtainFolderByFolderId(session.value.folder_id).then((folders) {
               FolderData folderData = folders[0];
               folderName.value = folderData.f_name;
            });
        }

        print('waveformData begin... audio_path: ${session.value.audio_path}');
        // /data/user/0/com.xinyi.smart_translator/cache/zhiyi_record2script1754461803542.mp3
        if(audioType == 'old' && session.value.audio_path.trim() != '') {
          //等于old的时候再初始化player.
          playerController.preparePlayer(path: session.value.audio_path,
              shouldExtractWaveform: true, noOfSamples: 60).then((v) async {

            playerController.onExtractionProgress.listen((process) {
              print('extract process:: ${process}');
            });

            playerController.onCompletion.listen((_){
              audioPlay.value = false;
              playerController.seekTo(0);

            });

            playerController.onCurrentDurationChanged.listen((duration) {
              currentMillionSecondsDuration = duration;
              currentFileDuration.value = CommonUtil.formatMillisecondsToHHMMSS_ForMillSeconds(duration);
            });

            int audioFileLength = await playerController.getDuration(DurationType.max);
            print('audioFileLength ::${audioFileLength}');
            maxFileLengthDuration = audioFileLength;
            fileLengthInDuration.value = CommonUtil.formatMillisecondsToHHMMSS_ForMillSeconds(audioFileLength);
            // final currentDuration = await playerController.getDuration(DurationType.current);

            // playerController.setRate(1.0);
          });
        }


        print('waveformData end...');


      }
    });

  }


  void justifyAudioSpeed() {
    showpoupWindowSpeed(Get.context!);
  }


  void showpoupWindowSpeed (BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (context) => SafeArea(child: Container(
          width: Get.width,
          padding: EdgeInsets.all(20.h),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              InkWell(
                onTap: () {
                  audioRateValue = 0.75;
                  speed_icon_path.value = 'assets/images/icon_player_speed_075.svg';
                  playerController.setRate(0.75);
                  Get.back();
                },
                child: Container(
                  padding: EdgeInsets.all(10.w),
                  child: audioRateValue == 0.75 ? Text('0.75',style: TextStyle(color: AppColors.app_base_theme_color),): Text('0.75'),
                ),
              ),
              CommonWidgets.getMyDivider(),
              InkWell(
                onTap: () {
                  audioRateValue = 1;
                  speed_icon_path.value = 'assets/images/icon_player_speed_1.svg';
                  playerController.setRate(1);
                  Get.back();
                },
                child: Container(
                  padding: EdgeInsets.all(10.w),
                  child: audioRateValue == 1 ? Text('1.0',style: TextStyle(color: AppColors.app_base_theme_color),) : Text('1.0'),
                ),
              )
              ,
              CommonWidgets.getMyDivider(),
              InkWell(
                onTap: () {
                  audioRateValue = 1.25;
                  speed_icon_path.value = 'assets/images/icon_player_speed_125.svg';
                  playerController.setRate(1.25);

                  Get.back();
                },
                child: Container(
                  padding: EdgeInsets.all(10.w),
                  child: audioRateValue == 1.25 ? Text('1.25',style: TextStyle(color: AppColors.app_base_theme_color),) : Text('1.25'),
                ),
              ),
              CommonWidgets.getMyDivider(),
              InkWell(
                onTap: () {
                  audioRateValue = 1.5;
                  speed_icon_path.value = 'assets/images/icon_player_speed_15.svg';
                  playerController.setRate(1.5);
                  Get.back();
                },
                child: Container(
                  padding: EdgeInsets.all(10.w),
                  child: audioRateValue == 1.5 ?  Text('1.5',style: TextStyle(color: AppColors.app_base_theme_color),) : Text('1.5'),
                ),
              ),
              CommonWidgets.getMyDivider(),
              InkWell(
                onTap: () {
                  audioRateValue = 1.75;
                  speed_icon_path.value = 'assets/images/icon_player_speed_175.svg';
                  playerController.setRate(1.75);
                  Get.back();
                },
                child: Container(
                  padding: EdgeInsets.all(10.w),
                  child: audioRateValue == 1.75? Text('1.75',style: TextStyle(color: AppColors.app_base_theme_color)): Text('1.75'),
                ),
              ),
              CommonWidgets.getMyDivider(),
              InkWell(
                onTap: () {
                  audioRateValue = 2;
                  speed_icon_path.value = 'assets/images/icon_player_speed_20.svg';
                  playerController.setRate(2);
                  Get.back();
                },
                child: Container(
                  padding: EdgeInsets.all(10.w),
                  child: Text('2.0'),
                ),
              )
            ],
          ),
        )),
        backgroundColor: Colors.white

    );
  }

  void forwardSeconds10() {
    int seekPosition = currentMillionSecondsDuration + 10 * 1000;
    if (seekPosition >= maxFileLengthDuration) {
      playerController.seekTo(maxFileLengthDuration);
    } else {
      playerController.seekTo(seekPosition);
    }

  }

  void backwardSeconds10() {
    int seconds = (currentMillionSecondsDuration/1000).toInt();
    if (seconds <= 10) {
      playerController.seekTo(0);
    } else {
      int seekPosition = currentMillionSecondsDuration - 10 * 1000;
      playerController.seekTo(seekPosition);
    }
  }


  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
    HomeController homeController = Get.find<HomeController>();
    homeController.refreshAudioFiles();

    if (scrollController !=  null) {
      scrollController.removeListener(_onScroll);
      scrollController.dispose();
    }

    if(playerController != null) {
      playerController.dispose();
    }

    WakelockPlus.disable();
  }

  void onPageChanged(int pageIndex) {
    if (pageIndex == 0) {
      summeryChecked.value = true;
      recordSCriptChecked.value = false;
      aiAnswerChecked.value = false;
    } else if (pageIndex == 1) {
      summeryChecked.value = false;
      recordSCriptChecked.value = true;
      aiAnswerChecked.value = false;
    } else {
      summeryChecked.value = false;
      recordSCriptChecked.value = false;
      aiAnswerChecked.value = true;
    }
  }


  void changeSessionName() {
        CommonWidgets.showConfirmDialogWithTextFiled(Get.context!,DataCallBack(
          confirmCallBack: (v) {
              if (v == '') {
                 Tips.showToast('不允许输入为空文件名.');
              } else {
                 DbDAOHelper().updateSessionNameBySessionId(int.parse(sessionId!), v);
                 loadData();
              }
          },
          cancleCallBack: (v) {

          }
        ),'编辑文件名');
  }


  void playAudioFromDeviceFile () async {
    playerController.startPlayer();
    playerController.setFinishMode(finishMode: FinishMode.pause);
    audioPlay.value = true;
  }

  void pauseAudioFromDeviceFile () async {
    playerController.pausePlayer();
    audioPlay.value = false;
  }

  void showpoupWindowMore (BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (context) => SafeArea(child: Container(
          width: Get.width,
          padding: EdgeInsets.all(20.h),
          color: AppColors.poup_window_bg_color,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              InkWell(
                onTap: () {
                  Get.back();
                  moveFolder();

                },
                child: Container(
                  padding: EdgeInsets.all(17.w),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(10)),
                      color: Colors.white
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Image.asset('assets/images/icon_menu_moving_folder.png',width: 24.w,height: 24.h,),
                      SizedBox(width: 11.w,),
                      Text('移动到文件夹',style: TextStyle(
                          fontSize: 16.sp
                      ))
                    ],
                  ),
                ),
              ),
              SizedBox(height: 10.h,),
              InkWell(
                onTap: () {
                  Get.back();
                  findOrReplace();
                },
                child: Container(
                  padding: EdgeInsets.all(17.w),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(10)),
                      color: Colors.white
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Image.asset('assets/images/icon_record_script_search_replace.png',width: 24.w,height: 24.h,),
                      SizedBox(width: 11.w,),
                      Text('查找和替换',style: TextStyle(
                          fontSize: 16.sp
                      ))
                    ],
                  ),
                ),
              ),
              SizedBox(height: 10.h,),
              InkWell(
                onTap: () {
                  RecordTransciptSummeryController  summaryController =  Get.find<RecordTransciptSummeryController>();
                  summaryController.generateSummery();
                  Get.back();
                },
                child:  Container(
                  padding: EdgeInsets.all(17.w),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(10)),
                      color: Colors.white
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Image.asset('assets/images/icon_record_script_resumerize.png',width: 24.w,height: 24.h,),
                      SizedBox(width: 11.w,),
                      Text('重新总结',style: TextStyle(
                          fontSize: 16.sp
                      ))
                    ],
                  ),
                ),
              ),
              SizedBox(height: 10.h,),
              Container(
                padding: EdgeInsets.all(17.w),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(10)),
                    color: Colors.white
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Image.asset('assets/images/icon_record_script_rescript.png',width: 24.w,height: 24.h,),
                    SizedBox(width: 11.w,),
                    Text('重新转写',style: TextStyle(
                        fontSize: 16.sp
                    ))
                  ],
                ),
              ),
              SizedBox(height: 10.h,),
              InkWell(
                onTap: () {
                  Get.back();
                  moveToRubbish();
                  Future.delayed(Duration(seconds: 1),() {
                    Tips.showToast('文件移动成功.');
                    quite();
                  });
                },
                child: Container(
                  padding: EdgeInsets.all(17.w),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(10)),
                      color: Colors.white
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Image.asset('assets/images/icon_menu_delete.png',width: 24.w,height: 24.h,),
                      SizedBox(width: 11.w,),
                      Text('移动到回收站',style: TextStyle(
                          fontSize: 16.sp
                      ))
                    ],
                  ),
                ),
              ),
            ],
          ),
        )),
        backgroundColor: Colors.white
    );
  }


  void showpoupWindowExport (BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (context) => SafeArea(child: Container(
          width: Get.width,
          padding: EdgeInsets.all(20.h),
          color: AppColors.poup_window_bg_color,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              InkWell(
                onTap: () {
                  exportAudio();
                },
                child: Container(
                  padding: EdgeInsets.all(17.w),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(10)),
                      color: Colors.white
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Image.asset('assets/images/icon_menu_export_audio.png',width: 24.w,height: 24.h,),
                      SizedBox(width: 11.w,),
                      Text('导出音频',style: TextStyle(
                          fontSize: 16.sp
                      ))
                    ],
                  ),
                ),
              ),
              SizedBox(height: 10.h,),
              InkWell(
                onTap: () {
                  exportTranscript();
                },
                child: Container(
                  padding: EdgeInsets.all(17.w),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(10)),
                      color: Colors.white
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Image.asset('assets/images/icon_menu_export_script.png',width: 24.w,height: 24.h,),
                      SizedBox(width: 11.w,),
                      Text('导出转写',style: TextStyle(
                          fontSize: 16.sp
                      ))
                    ],
                  ),
                ),
              ),
              SizedBox(height: 10.h,),
              InkWell(
                onTap: () {
                   exportSummery();
                },
                child: Container(
                  padding: EdgeInsets.all(17.w),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(10)),
                      color: Colors.white
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Image.asset('assets/images/icon_menu_export_summary.png',width: 24.w,height: 24.h,),
                      SizedBox(width: 11.w,),
                      Text('导出总结',style: TextStyle(
                          fontSize: 16.sp
                      ))
                    ],
                  ),
                ),
              )
            ],
          ),
        )),
        backgroundColor: Colors.white

    );
  }


  void moveToRubbish() {
    // sessionId
    DbDAOHelper().updateSessionFolderBySessionId(int.parse(sessionId!), -1);
    Tips.showToast('已经移动到回收站');
  }



  void quite() {
    RecordTranscriptViewRecordingController recordingController =  Get.find<RecordTranscriptViewRecordingController>();
    if (recordingController.audioService.isPlaying.value) {
      CommonWidgets.showConfirmDialog(Get.context!, '提示', '返回后将关闭并退出会议转写', '退出', '悬浮窗显示', DataCallBack(
          confirmCallBack: (v) {

            //这里涉及到嵌套controller需要手动删除。
            /*RecordTranscriptViewRecordingController recordTranscriptViewRecordingController = Get.find<RecordTranscriptViewRecordingController>();
            if (recordTranscriptViewRecordingController != null) {
              recordTranscriptViewRecordingController.onClose();
            }*/

            Get.delete<RecordTranscriptViewRecordingController>();
            Get.delete<RecordTranscriptViewAiController>();
            Get.delete<RecordTransciptSummeryController>();
            // Get.delete<RecordscriptDetailController>();

            Get.back(); //退出转写.
          },
          cancleCallBack: (v) {
            FlutterOverlayWindow.isActive().then((show) async {
              if (show) {
                FlutterAppMinimizerPlus.minimizeApp();
              } else {
                showFloatingWindow(Get.context!);
              }
            });
          }
      ),barrierDismissible: true);
    } else {
      //这里涉及到嵌套controller需要手动删除。
      /*RecordTranscriptViewRecordingController recordTranscriptViewRecordingController = Get.find<RecordTranscriptViewRecordingController>();
      if (recordTranscriptViewRecordingController != null) {
        recordTranscriptViewRecordingController.onClose();
      }*/

      Get.delete<RecordTranscriptViewRecordingController>();
      Get.delete<RecordTranscriptViewAiController>();
      Get.delete<RecordTransciptSummeryController>();
      // Get.delete<RecordscriptDetailController>();

      Get.back();
    }
  }


  void showFloatingWindow (BuildContext context) async {
    RecordTranscriptViewRecordingController recordingController =  Get.find<RecordTranscriptViewRecordingController>();
    if(!recordingController.audioService.isPlaying.value) {
      Tips.showToast('请先开始录音.');
      return;
    }

    bool status = await FlutterOverlayWindow.isPermissionGranted();
    if (!status) {
      bool? result = await FlutterOverlayWindow.requestPermission();
      if (result!) {
        Tips.showToast('已经获取到权限');
      } else {
        Tips.showToast('未获取到授权.');
        return;
      }
    }

    FlutterOverlayWindow.isActive().then((show) async {
      if(show) {
        await FlutterOverlayWindow.closeOverlay();
      } else {
        await FlutterOverlayWindow.showOverlay(
          flag: OverlayFlag.defaultFlag,
          visibility: NotificationVisibility.visibilityPublic,
          width: (CommonUtil.getScreenSize_ofWidth(context)*0.95).toInt(),
          height: (MediaQuery.of(context).size.height * 0.7).toInt(),
          startPosition: const OverlayPosition(0, -259),
          overlayTitle: "SmartTranslator",
          overlayContent: '浮窗运行中',
          positionGravity: PositionGravity.left,
          enableDrag: true,
        );
        FlutterAppMinimizerPlus.minimizeApp();


      }
    });
  }


  void moveFolder({bool isQuitePage = true}) {
    showModalBottomSheet(
        isScrollControlled:true,
        context: Get.context!,
        builder: (context) => StatefulBuilder(builder: (contex,setState) {
          return SafeArea(child: SingleChildScrollView(
            child: Obx(()=>Container(
              width: Get.width,
              padding: EdgeInsets.all(20.h),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.only(topLeft: Radius.circular(10),topRight: Radius.circular(10)),
                color: AppColors.poup_window_bg_color,
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text('移动到',style: TextStyle(
                          fontSize: 14.sp,
                          color: AppColors.poupwindow_title_font_color
                      ),),
                      InkWell(
                        onTap: () {
                          Get.back();
                        },
                        child: Image.asset('assets/images/landscape_close_btn.png',width: 15.w,height: 15.h,),
                      )
                    ],
                  ),
                  SizedBox(height: 14.h,),
                  CommonWidgets.getMyDivider(),
                  SizedBox(height: 16.h,),
                  Row(
                    children: [
                      Text('文件夹',style: TextStyle(
                          fontSize: 14.sp,
                          color: AppColors.poupwindow_title_font_color
                      ),),
                    ],
                  ),
                  SizedBox(height: 10.h,),
                  Container(
                    height: 170.h,
                    child: ListView.builder(itemBuilder: (context,index) {
                      ExtendFolderData folderItem = folderCollections.value[index];
                      return InkWell(
                        onTap: () {
                          allFolerHasChecked.value = false;
                          folderCollections.value.forEach((item) {
                            if (item.id == folderItem.id) {
                              item.isChecked = true;
                            } else {
                              item.isChecked = false;
                            }
                          });
                          // 刷新页面.
                          setState((){});
                        },
                        child: Container(
                          padding: EdgeInsets.all(12.w),
                          child: Column(
                            children: [
                              Row(
                                children: [
                                  folderItem.isChecked ? Image.asset('assets/images/icon_record_script_item_checked.png',width: 16.w,height: 11.h):
                                  SizedBox(width: 16.w,),
                                  SizedBox(width: 33.w,),
                                  Text('${folderItem.f_name}', style: TextStyle(
                                      fontSize: 16.sp,
                                      color: AppColors.app_base_theme_color
                                  ),)
                                ],
                              ),
                              SizedBox(height: 12.h,),
                              CommonWidgets.getMyDivider(),
                            ],
                          ),
                        ),
                      );
                    },
                        itemCount: folderCollections.value.length),
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(10))
                    ),
                  ),
                  SizedBox(height: 16.h,),
                  InkWell(
                    onTap: () {
                      addNewFolder();
                    },
                    child: Container(
                      padding: EdgeInsets.all(12.w),
                      child: Row(
                        children: [
                          Text('新建文件夹...', style: TextStyle(
                              fontSize: 16.sp,
                              color: AppColors.app_base_theme_color
                          )),
                        ],
                      ),
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.all(Radius.circular(10))
                      ),
                    ),
                  ),
                  SizedBox(height: 16.h,),
                  Row(
                    children: [
                      Text('文件夹',style: TextStyle(
                          fontSize: 14.sp,
                          color: AppColors.poupwindow_title_font_color
                      ),),
                    ],
                  ),
                  SizedBox(height: 16.h,),
                  InkWell(
                    onTap: () {
                      allFolerHasChecked.value = !allFolerHasChecked.value;
                      folderCollections.value.forEach((item) {
                        item.isChecked = false;
                      });
                      setState((){});
                    },
                    child: Container(
                      padding: EdgeInsets.all(12.w),
                      child:  Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            children: [
                              Image.asset('assets/images/icon_slideside_folder.png',width: 16.w,height: 16.h),
                              SizedBox(width: 10.w,),
                              Text('全部文件夹', style: TextStyle(
                                  fontSize: 16.sp,
                                  color: AppColors.app_base_theme_color
                              ),)
                            ],
                          ),
                          allFolerHasChecked.value ?
                          Image.asset('assets/images/icon_record_script_item_checked.png',width: 16.w,height: 11.h):
                          SizedBox(height: 16.w,)
                        ],
                      ),
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.all(Radius.circular(10))
                      ),
                    ),
                  ),
                  SizedBox(height: 20.h,),
                  Container(
                    width: Get.width,
                    child: ElevatedButton(onPressed: () {
                      moveFile2NewFolder(isQuitePage);

                    }, child: Text('移动')
                    ),
                  )
                ],
              ),
            )),
          ));

        }),
        backgroundColor: Colors.white
    );
  }




  void addNewFolder() {
    CommonWidgets.showConfirmDialogWithTextFiled(Get.context!, DataCallBack(
        confirmCallBack: (v) {
          DbDAOHelper().addFolder(v);
          //刷新文件夹列表.
          getCustomerFolders();
        },
        cancleCallBack: (v) {
        }
    ),'文件夹名称');
  }




  void getCustomerFolders() {
    DbDAOHelper().obtainAllFolders().then((folders) {
      folderCollections.clear();
      folders.forEach((folder) {
        folderCollections.add(
        ExtendFolderData(id: folder.id,
          user_id: folder.user_id,
          f_name: folder.f_name,
          create_time: folder.create_time,
          update_time: folder.update_time
        ));
      });
    });
  }



  void moveFile2NewFolder(bool isQuitPage) {
    int folderId = 100000;
    if(allFolerHasChecked.value == true)  {
      folderId = 100000;
    } else {
      folderCollections.value.forEach((item) {
          if (item.isChecked == true) {
            folderId = item.id;
          }
      });
    }

    DbDAOHelper().updateSessionFolderBySessionId(int.parse(sessionId!), folderId);
    Get.back();

    if (isQuitPage) {
      Future.delayed(Duration(seconds: 1),() {
        Tips.showToast('文件移动成功.');
        quite();
      });

    } else {
      loadData();
    }


  }


  void findOrReplace() {
    CommonWidgets.showSearchOrReplaceDialog(Get.context!, DataCallBack(
        confirmCallBack: (v) { //上一个
        },
        cancleCallBack: (v) { //下一个.
        },
        businessCallBack: (v) { //替换

        },
        errorCallBack: (v) { // 输入框内容变化.
          print('输入框内容: ${v}');
          RecordTransciptSummeryController recordTransciptSummeryController = Get.find<RecordTransciptSummeryController>();
          String summaryContent = recordTransciptSummeryController.summaryContent.value;
        }
    ));
  }


  void exportAudio() {
      Get.back();
      showModalBottomSheet(
          isScrollControlled:true,
          context: Get.context!,
          builder: (context) => StatefulBuilder(builder: (contex,setState) {
            return SafeArea(child: SingleChildScrollView(
              child: Obx(()=>Container(
                width: Get.width,
                padding: EdgeInsets.all(20.h),
                color: AppColors.poup_window_bg_color,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text('导出音频',style: TextStyle(
                            fontSize: 14.sp,
                            color: AppColors.poupwindow_title_font_color
                        ),),
                        InkWell(
                          onTap: () {
                            Get.back();
                          },
                          child: Image.asset('assets/images/landscape_close_btn.png',width: 15.w,height: 15.h,),
                        )
                      ],
                    ),
                    SizedBox(height: 14.h,),
                    CommonWidgets.getMyDivider(),
                    SizedBox(height: 16.h,),
                    Row(
                      children: [
                        Text('音频格式',style: TextStyle(
                            fontSize: 14.sp,
                            color: AppColors.poupwindow_title_font_color
                        ),),
                      ],
                    ),
                    SizedBox(height: 16.h,),
                    Container(
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.all(Radius.circular(10))
                      ),
                      padding: EdgeInsets.all(12.w),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          InkWell(
                            onTap: () {
                              exportMP3Checked.value = true;
                              exportWAVChecked.value = false;
                              setState((){});
                            },
                            child: Container(
                              child:  Row(
                                children: [
                                  exportMP3Checked.value ?
                                  Image.asset('assets/images/icon_record_script_item_checked.png',width: 16.w,height: 11.h):
                                  SizedBox(width: 16.w,),
                                  SizedBox(width: 14.w,),
                                  Text('MP3', style: TextStyle(
                                      fontSize: 16.sp,
                                      color: AppColors.app_base_theme_color
                                  ),),

                                ],
                              ),
                            ),
                          )
                          ,
                          SizedBox(height: 10.h,),
                          CommonWidgets.getMyDivider(),
                          SizedBox(height: 10.h,),
                          InkWell(
                            onTap: () {
                              exportMP3Checked.value = false;
                              exportWAVChecked.value = true;
                              setState((){});
                            },
                            child: Container(
                              child:  Row(
                                children: [
                                  exportWAVChecked.value ?
                                  Image.asset('assets/images/icon_record_script_item_checked.png',width: 16.w,height: 11.h):
                                  SizedBox(width: 16.w,),
                                  SizedBox(width: 14.w,),
                                  Text('WAV', style: TextStyle(
                                      fontSize: 16.sp,
                                      color: AppColors.app_base_theme_color
                                  ),),

                                ],
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                    SizedBox(height: 20.h,),
                    Container(
                      width: Get.width,
                      child: ElevatedButton(onPressed: () {
                          executeExportAudio();

                      }, child: Text('导出')
                      ),
                    )
                  ],
                ),
              )),
            ));

          }),
          backgroundColor: Colors.white
      );
  }

  void exportTranscript() {
    Get.back();
    showModalBottomSheet(
        isScrollControlled:true,
        context: Get.context!,
        builder: (context) => StatefulBuilder(builder: (contex,setState) {
          return SafeArea(child: SingleChildScrollView(
            child: Obx(()=>Container(
              width: Get.width,
              padding: EdgeInsets.all(20.h),
              color: AppColors.poup_window_bg_color,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text('导出转写',style: TextStyle(
                          fontSize: 14.sp,
                          color: AppColors.poupwindow_title_font_color
                      ),),
                      InkWell(
                        onTap: () {
                          Get.back();
                        },
                        child: Image.asset('assets/images/landscape_close_btn.png',width: 15.w,height: 15.h,),
                      )
                    ],
                  ),
                  SizedBox(height: 14.h,),
                  CommonWidgets.getMyDivider(),
                  SizedBox(height: 16.h,),
                  Row(
                    children: [
                      Text('导出为',style: TextStyle(
                          fontSize: 14.sp,
                          color: AppColors.poupwindow_title_font_color
                      ),),
                    ],
                  ),
                  SizedBox(height: 16.h,),
                  Container(
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(10))
                    ),
                    padding: EdgeInsets.all(12.w),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        InkWell(
                          onTap: () {
                            exportSummeryTxt.value = true;
                            exportSummerySRT.value = false;
                            exportSummeryDocx.value = false;
                            exportSummeryPDF.value = false;
                            setState((){});
                          },
                          child: Container(
                            child:  Row(
                              children: [
                                exportSummeryTxt.value ?
                                Image.asset('assets/images/icon_record_script_item_checked.png',width: 16.w,height: 11.h):
                                SizedBox(width: 16.w,),
                                SizedBox(width: 14.w,),
                                Text('TXT', style: TextStyle(
                                    fontSize: 16.sp,
                                    color: AppColors.app_base_theme_color
                                ),),

                              ],
                            ),
                          ),
                        ),
                        SizedBox(height: 10.h,),
                        CommonWidgets.getMyDivider(),
                        SizedBox(height: 10.h,),
                        InkWell(
                          onTap: () {
                            exportSummeryTxt.value = false;
                            exportSummerySRT.value = true;
                            exportSummeryDocx.value = false;
                            exportSummeryPDF.value = false;
                            setState((){});
                          },
                          child: Container(
                            child:  Row(
                              children: [
                                exportSummerySRT.value ?
                                Image.asset('assets/images/icon_record_script_item_checked.png',width: 16.w,height: 11.h):
                                SizedBox(width: 16.w,),
                                SizedBox(width: 14.w,),
                                Text('SRT', style: TextStyle(
                                    fontSize: 16.sp,
                                    color: AppColors.app_base_theme_color
                                ),),

                              ],
                            ),
                          ),
                        ),
                        SizedBox(height: 10.h,),
                        CommonWidgets.getMyDivider(),
                        SizedBox(height: 10.h,),
                        InkWell(
                          onTap: () {
                            exportSummeryTxt.value = false;
                            exportSummerySRT.value = false;
                            exportSummeryDocx.value = true;
                            exportSummeryPDF.value = false;
                            setState((){});
                          },
                          child: Container(
                            child:  Row(
                              children: [
                                exportSummeryDocx.value ?
                                Image.asset('assets/images/icon_record_script_item_checked.png',width: 16.w,height: 11.h):
                                SizedBox(width: 16.w,),
                                SizedBox(width: 14.w,),
                                Text('DOX', style: TextStyle(
                                    fontSize: 16.sp,
                                    color: AppColors.app_base_theme_color
                                ),),

                              ],
                            ),
                          ),
                        ),
                        SizedBox(height: 10.h,),
                        CommonWidgets.getMyDivider(),
                        SizedBox(height: 10.h,),
                        InkWell(
                          onTap: () {
                            exportSummeryTxt.value = false;
                            exportSummerySRT.value = false;
                            exportSummeryDocx.value = false;
                            exportSummeryPDF.value = true;
                            setState((){});
                          },
                          child: Container(
                            child:  Row(
                              children: [
                                exportSummeryPDF.value ?
                                Image.asset('assets/images/icon_record_script_item_checked.png',width: 16.w,height: 11.h):
                                SizedBox(width: 16.w,),
                                SizedBox(width: 14.w,),
                                Text('PDF', style: TextStyle(
                                    fontSize: 16.sp,
                                    color: AppColors.app_base_theme_color
                                ),),

                              ],
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                  SizedBox(height: 20.h,),
                  Row(
                    children: [
                      Text('分享内容',style: TextStyle(
                          fontSize: 14.sp,
                          color: AppColors.poupwindow_title_font_color
                      ),),
                    ],
                  ),
                  SizedBox(height: 16.h,),
                  Container(
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(10))
                    ),
                    padding: EdgeInsets.all(12.w),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        InkWell(
                          onTap: () {

                            setState((){});
                          },
                          child: Container(
                            child:  Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text('带时间戳', style: TextStyle(
                                    fontSize: 16.sp,
                                    color: AppColors.app_base_theme_color
                                ),),
                                Container(
                                  height: 24.h,
                                  child: Switch(
                                      value: exportTranscript_withTime.value,
                                      onChanged: (v) {
                                        exportTranscript_withTime.value = v;
                                      },
                                      inactiveTrackColor: AppColors.swith_inactive_bg_color,
                                      activeTrackColor: AppColors.app_base_theme_color,
                                      trackOutlineWidth: WidgetStateProperty.all(0)
                                  ),
                                )

                              ],
                            ),
                          ),
                        ),
                        SizedBox(height: 10.h,),
                        CommonWidgets.getMyDivider(),
                        SizedBox(height: 10.h,),
                        InkWell(
                          onTap: () {

                            setState((){});
                          },
                          child: Container(
                            child:  Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text('带讲话人名称', style: TextStyle(
                                    fontSize: 16.sp,
                                    color: AppColors.app_base_theme_color
                                ),),
                                Container(
                                  height: 24.h,
                                  child: Switch(
                                      value: exportTranscript_withName.value,
                                      onChanged: (v) {
                                        exportTranscript_withName.value = v;

                                      },
                                      inactiveTrackColor: AppColors.swith_inactive_bg_color,
                                      activeTrackColor: AppColors.app_base_theme_color,
                                      trackOutlineWidth: WidgetStateProperty.all(0)
                                  ),
                                )

                              ],
                            ),
                          ),
                        ),

                      ],
                    ),
                  ),
                  SizedBox(height: 16.h,),
                  Container(
                    width: Get.width,
                    child: ElevatedButton(onPressed: () {
                        executeExportTranscript();

                    }, child: Text('导出')
                    ),
                  )
                ],
              ),
            )),
          ));

        }),
        backgroundColor: Colors.white
    );
  }


  void exportSummery() {
    Get.back();
    showModalBottomSheet(
        isScrollControlled:true,
        context: Get.context!,
        builder: (context) => StatefulBuilder(builder: (contex,setState) {
          return SafeArea(child: SingleChildScrollView(
            child: Obx(()=>Container(
              width: Get.width,
              padding: EdgeInsets.all(20.h),
              color: AppColors.poup_window_bg_color,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text('导出总结',style: TextStyle(
                          fontSize: 14.sp,
                          color: AppColors.poupwindow_title_font_color
                      ),),
                      InkWell(
                        onTap: () {
                          Get.back();
                        },
                        child: Image.asset('assets/images/landscape_close_btn.png',width: 15.w,height: 15.h,),
                      )
                    ],
                  ),
                  SizedBox(height: 14.h,),
                  CommonWidgets.getMyDivider(),
                  SizedBox(height: 16.h,),
                  Row(
                    children: [
                      Text('导出为',style: TextStyle(
                          fontSize: 14.sp,
                          color: AppColors.poupwindow_title_font_color
                      ),),
                    ],
                  ),
                  SizedBox(height: 16.h,),
                  Container(
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(10))
                    ),
                    padding: EdgeInsets.all(12.w),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        InkWell(
                          onTap: () {
                            exportSummeryTxt.value = true;
                            exportSummerySRT.value = false;
                            exportSummeryDocx.value = false;
                            exportSummeryPDF.value = false;
                            setState((){});
                          },
                          child: Container(
                            child:  Row(
                              children: [
                                exportSummeryTxt.value ?
                                Image.asset('assets/images/icon_record_script_item_checked.png',width: 16.w,height: 11.h):
                                SizedBox(width: 16.w,),
                                SizedBox(width: 14.w,),
                                Text('TXT', style: TextStyle(
                                    fontSize: 16.sp,
                                    color: AppColors.app_base_theme_color
                                ),),

                              ],
                            ),
                          ),
                        ),
                        SizedBox(height: 10.h,),
                        CommonWidgets.getMyDivider(),
                        SizedBox(height: 10.h,),
                        InkWell(
                          onTap: () {
                            exportSummeryTxt.value = false;
                            exportSummerySRT.value = false;
                            exportSummeryDocx.value = true;
                            exportSummeryPDF.value = false;
                            setState((){});
                          },
                          child: Container(
                            child:  Row(
                              children: [
                                exportSummeryDocx.value ?
                                Image.asset('assets/images/icon_record_script_item_checked.png',width: 16.w,height: 11.h):
                                SizedBox(width: 16.w,),
                                SizedBox(width: 14.w,),
                                Text('DOX', style: TextStyle(
                                    fontSize: 16.sp,
                                    color: AppColors.app_base_theme_color
                                ),),

                              ],
                            ),
                          ),
                        ),
                        SizedBox(height: 10.h,),
                        CommonWidgets.getMyDivider(),
                        SizedBox(height: 10.h,),
                        InkWell(
                          onTap: () {
                            exportSummeryTxt.value = false;
                            exportSummerySRT.value = false;
                            exportSummeryDocx.value = false;
                            exportSummeryPDF.value = true;
                            setState((){});
                          },
                          child: Container(
                            child:  Row(
                              children: [
                                exportSummeryPDF.value ?
                                Image.asset('assets/images/icon_record_script_item_checked.png',width: 16.w,height: 11.h):
                                SizedBox(width: 16.w,),
                                SizedBox(width: 14.w,),
                                Text('PDF', style: TextStyle(
                                    fontSize: 16.sp,
                                    color: AppColors.app_base_theme_color
                                ),),

                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  SizedBox(height: 20.h,),
                  Container(
                    width: Get.width,
                    child: ElevatedButton(onPressed: () {
                       executeExportSummery();
                    }, child: Text('导出')
                    ),
                  )
                ],
              ),
            )),
          ));

        }),
        backgroundColor: Colors.white
    );
  }



  void executeExportAudio() async {
    if (!exportMP3Checked.value && !exportWAVChecked.value) {
       Tips.showToast('请选择导出音频类型.');
    } else {
       if (exportMP3Checked.value) {
         Tips.showToast('正在导出mp3格式,请稍后.');
         String wavPath = session.value.audio_path;
         String mp3path = session.value.audio_path.replaceAll('wav', 'mp3');

         await checkAndDeleteFile(mp3path);

         FFmpegKit.execute('-i ${wavPath} -codec:a libmp3lame -q:a 2 ${mp3path}').then((session) async {
           final returnCode = await session.getReturnCode();
           if (ReturnCode.isSuccess(returnCode)) {
             // SUCCESS
             print('转换成功....');
             Tips.showToast('转换成功.');

             shareAudioFile(mp3path);
           } else if (ReturnCode.isCancel(returnCode)) {
             // CANCEL
             print('转换取消....');
             Tips.showToast('转换取消.');
           } else {
             // ERROR
             print('转换错误....');
             Tips.showToast('转换错误.');
           }
         });

       } else {
         Tips.showToast('正在导出wav格式,请稍后.');
         shareAudioFile(session.value.audio_path);
       }
    }
  }


  // 分享图片
  static shareAudioFile (audioPath) async {
    final fileItem = XFile(audioPath);
    final params = ShareParams(text: '分享图片', files: [fileItem]);
    Get.back();
    await SharePlus.instance.share(params);

  }


  void executeExportSummery() {
      DbDAOHelper().getSummaryBySessionId(session.value.id.toString()).then((summery) async {
         if (summery != null) {
            String summeryContent = utf8.decode(summery.s_content);
            if (summeryContent == null || summeryContent.trim() == '') {
              Tips.showToast('未找到总结内容,请先生成.');
              return;
            }

            //将summery 的富文本格式转换成纯文本格式.
            if (summeryContent.startsWith('[{')) {
              summeryContent = quill.Document.fromJson(json.decode(summeryContent)).toPlainText();
            }


            if (exportSummeryTxt.value) { //导出文本.
              final tempDir = await getTemporaryDirectory();
              String summeryFilePath = '${tempDir.path}/${session.value.session_name}_summery.txt';

              // await checkAndDeleteFile(summeryFilePath);

              final summeryFile = File(summeryFilePath);
              try {
                await summeryFile.writeAsString(summeryContent);
                print('文件写入成功！');
              } catch (e) {
                print('写入失败: $e');
              }

              shareAudioFile(summeryFilePath);
            } else if(exportSummeryDocx.value) {
              final tempDir = await getTemporaryDirectory();
              String summeryDocxPath = '${tempDir.path}/${session.value.session_name}_summery.docx';


              final data = await rootBundle.load('assets/templates/summery_template.docx');
              final bytes = data.buffer.asUint8List();
              final docx = await DocxTemplate.fromBytes(bytes);


              Content c = Content();
              c..add(TextContent("summeryTitle", "${session.value.session_name}"))
              ..add(TextContent('createTime', CommonUtil.formatCustomWeekday(session.value.create_time)))
              ..add(TextContent('summeryContent', summeryContent));

              final d = await docx.generate(c);
              final of = File(summeryDocxPath);

              if (d != null) await of.writeAsBytes(d);

              shareAudioFile(summeryDocxPath);

            } else if(exportSummeryPDF.value) {
              final tempDir = await getTemporaryDirectory();
              String summeryPDFPath = '${tempDir.path}/${session.value.session_name}_summery.pdf';
              generatePDFforSummery(summeryPDFPath,summeryContent);
            }

         } else {
           Tips.showToast('未找到总结内容,请先生成.');
         }

      });

  }

  Future<void> checkAndDeleteFile(String filePath) async {
    try {
      final file = File(filePath);
      if (await file.exists()) {
        await file.delete();
        print('临时文件已删除: ${file.path}');
      } else {
        print('文件不存在: ${file.path}');
      }
    } catch(e) {
       e.printError();
    }
  }

  // 分块函数：按字符数分割文本（例如每 1000 字符一页）
  List<String> splitTextToPages(String text, int chunkSize) {
    List<String> chunks = [];
    for (int i = 0; i < text.length; i += chunkSize) {
      int end = (i + chunkSize) < text.length ? i + chunkSize : text.length;
      chunks.add(text.substring(i, end));
    }
    return chunks;
  }

  Future<void> generatePDFforSummery(String filePath,String summeryContent) async {
    print('summeryContent ::: ${summeryContent}');

    final pdf = pw.Document();
    final font = await pw.Font.ttf(await rootBundle.load('assets/fonts/NotoSerifSC[wght].ttf'));

    final textChunks = splitTextToPages(summeryContent,280);
    // 逐页添加
    for (var chunk in textChunks) {
      pdf.addPage(
        pw.Page(
          build: (context) {
            return pw.Column(
              crossAxisAlignment: pw.CrossAxisAlignment.start,
              children: [
                pw.Text('${session.value.session_name}', style: pw.TextStyle(fontSize: 40, font: font)),
                pw.SizedBox(height: 20),
                pw.Text('${CommonUtil.formatCustomWeekday(session.value.create_time)}', style: pw.TextStyle(fontSize: 20, font: font)),
                pw.SizedBox(height: 60),
                pw.Text(chunk, style: pw.TextStyle(fontSize: 20, font: font)),
              ],
            );
          },
        ),
      );
    }

    // 保存到文件
    final file = File(filePath);
    await file.writeAsBytes(await pdf.save());
    //await file.writeAsString(utf8.decode(await pdf.save()));

    print('PDF 已生成：${file.path}');

    shareAudioFile(filePath);
  }


  void executeExportTranscript() {
    // 查询transcript并重新组装总结.
    DbDAOHelper().obtainTranscriptsBySessionId(session.value.id).then((scripts) async {
      if(exportSummeryTxt.value) {
        String result = '';
        scripts.forEach((scriptItem) {
          if(exportTranscript_withName.value) {
            result = result + CommonUtil.getMMSSFormate(scriptItem.duration) +'  ' + scriptItem.speaker + '\n' + scriptItem.a_text+'\n';
          } else {
            result = result +  CommonUtil.getMMSSFormate(scriptItem.duration) +'\n'+ scriptItem.a_text+'\n';
          }

        });

        final tempDir = await getTemporaryDirectory();
        String summeryFilePath = '${tempDir.path}/${session.value.session_name}_script.txt';

        // await checkAndDeleteFile(summeryFilePath);

        final summeryFile = File(summeryFilePath);
        try {
          await summeryFile.writeAsString(result);
          print('文件写入成功！');
        } catch (e) {
          print('写入失败: $e');
        }

        shareAudioFile(summeryFilePath);


      } else if (exportSummerySRT.value) {
        String result = '';
        int index = 1;
        scripts.forEach((scriptItem) {
          if(exportTranscript_withName.value) {
            result = result + '${index}\n'+ CommonUtil.getMMSSFormate(scriptItem.duration) +'  ' + scriptItem.speaker + '\n' + scriptItem.a_text+'\n';
          } else {
            result = result + '${index}\n' + CommonUtil.getMMSSFormate(scriptItem.duration) +'\n'+ scriptItem.a_text+'\n';
          }
          index ++;
        });

        final tempDir = await getTemporaryDirectory();
        String summeryFilePath = '${tempDir.path}/${session.value.session_name}_script.srt';

        // await checkAndDeleteFile(summeryFilePath);

        final summeryFile = File(summeryFilePath);
        try {
          await summeryFile.writeAsString(result);
          print('文件写入成功！');
        } catch (e) {
          print('写入失败: $e');
        }

        shareAudioFile(summeryFilePath);

      } else if (exportSummeryDocx.value) {

        final tempDir = await getTemporaryDirectory();
        String summeryDocxPath = '${tempDir.path}/${session.value.session_name}_script.docx';


        final data = await rootBundle.load('assets/templates/transcript_template.docx');
        final bytes = data.buffer.asUint8List();
        final docx = await DocxTemplate.fromBytes(bytes);


        String result = '';
        scripts.forEach((scriptItem) {
          if(exportTranscript_withName.value) {
            result = result + CommonUtil.getMMSSFormate(scriptItem.duration) +'  ' + scriptItem.speaker + '\n' + scriptItem.a_text+'\n';
          } else {
            result = result +  CommonUtil.getMMSSFormate(scriptItem.duration) +'\n'+ scriptItem.a_text+'\n';
          }

        });


        print('export transcript result ---------> ${result}');
        Content c = Content();
        c..add(TextContent("session_name", "${session.value.session_name}"))
          ..add(TextContent('sessionTime', CommonUtil.formatCustomWeekday(session.value.create_time)))
          ..add(TextContent('script_records', result));

        final d = await docx.generate(c);
        final of = File(summeryDocxPath);

        if (d != null) await of.writeAsBytes(d);

        shareAudioFile(summeryDocxPath);

      } else if(exportSummeryPDF.value) {
        final tempDir = await getTemporaryDirectory();
        String summeryPDFPath = '${tempDir.path}/${session.value.session_name}_script.pdf';

        String result = '';
        scripts.forEach((scriptItem) {
          if(exportTranscript_withName.value) {
            result = result + CommonUtil.getMMSSFormate(scriptItem.duration) +'  ' + scriptItem.speaker + '\n' + scriptItem.a_text+'\n';
          } else {
            result = result + CommonUtil.getMMSSFormate(scriptItem.duration) +'\n'+ scriptItem.a_text+'\n';
          }

        });

        generatePDFforScript(summeryPDFPath,result);

      }



    });
  }


  Future<void> generatePDFforScript(String filePath,String scriptContent) async {
    print('scriptContent ::: ${scriptContent}');

    final pdf = pw.Document();
    final font = await pw.Font.ttf(await rootBundle.load('assets/fonts/NotoSerifSC[wght].ttf'));

    final textChunks = splitTextToPages(scriptContent,280);
    // 逐页添加
    for (var chunk in textChunks) {
      pdf.addPage(
        pw.Page(
          build: (context) {
            return pw.Column(
              crossAxisAlignment: pw.CrossAxisAlignment.start,
              children: [
                pw.Text('${session.value.session_name}', style: pw.TextStyle(fontSize: 40, font: font)),
                pw.SizedBox(height: 20),
                pw.Text('${CommonUtil.formatCustomWeekday(session.value.create_time)}', style: pw.TextStyle(fontSize: 20, font: font)),
                pw.SizedBox(height: 60),
                pw.Text(chunk, style: pw.TextStyle(fontSize: 20, font: font)),
              ],
            );
          },
        ),
      );
    }

    // 保存到文件
    final file = File(filePath);
    await file.writeAsBytes(await pdf.save());
    //await file.writeAsString(utf8.decode(await pdf.save()));

    print('PDF 已生成：${file.path}');

    shareAudioFile(filePath);
  }


}



class ExtendFolderData extends FolderData {
  ExtendFolderData({required super.id, required super.user_id, required super.f_name, required super.create_time, required super.update_time});
  bool isChecked = false;
}



